package com.cskaoyan.shiro;

import com.cskaoyan.bean.Admin;
import com.cskaoyan.bean.AdminExample;
import com.cskaoyan.mapper.AdminMapper;
import com.cskaoyan.mapper.UserMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author heyyon
 */
@Component
public class CustomRealm extends AuthorizingRealm {
    @Autowired
    AdminMapper adminMapper;
    @Autowired
    UserMapper userMapper;
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
            throws AuthenticationException {
        
        MallToken token=(MallToken)authenticationToken; 
        AuthenticationInfo authenticationInfo = dealByType(token);
        return authenticationInfo;
    }

    private AuthenticationInfo dealByType(MallToken token) {
        String type=token.getType();
        String passwordFromDB=null;
        String username=null;
        if (type.contains("admin")) {
            username = token.getUsername();
            passwordFromDB = adminMapper.selectPasswordByName(username);
        } else {
            username=token.getUsername();
            passwordFromDB = userMapper.selectPasswordByName(username);
        } 
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username, passwordFromDB, this.getName());
        return authenticationInfo;
    }

    /**
     * @param principalCollection 
     * @return
     * 先根据name查询出admin对应的权限列表
     * 再根据权限列表查询权限名
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String usernmae= (String) principalCollection.getPrimaryPrincipal();
        AdminExample adminExample = new AdminExample();
        AdminExample.Criteria criteria=adminExample.createCriteria();
        if (usernmae != null) {
            criteria.andUsernameLike(usernmae);
        }
        Admin admin = adminMapper.selectByUsername(usernmae);
        List<String> permissions=new ArrayList<>();
        Integer[] roleIds = admin.getRoleIds();
        for (Integer roleId : roleIds) {
            List<String> list=adminMapper.selectPermissionByRoleId(roleId);
            permissions.addAll(list);
        }
        SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
        authorizationInfo.addStringPermissions(permissions);
        return authorizationInfo;
    }


}
